package com.ruoyi.system.waishu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 实际的调用外部外数接口
 */
@Slf4j
public abstract class AbstartctThirdDataService implements ThirdDataService, ApplicationContextAware {
    private static ApplicationContext context;

    /**
     * 抽象的交互类
     * @param req
     * @return
     */
    @Override
    public JSONObject call(ApiReq req) {
        prefix(req);
        JSONObject response = callService(req);
        suffix(response);
        return response;
    }

    protected void suffix(JSONObject response){};

    protected void prefix(ApiReq req){};

    protected JSONObject callService(ApiReq req){
        JSONObject result = new JSONObject();
        request(req);
        log.info("{}服务{}请求报文：{}",req.getReqId(),req.getApiCode()+"接口", JSON.toJSON(req));
        Mono<JSONObject> response = getWebClient(req);
        JSONObject jsonObject = response.block(Duration.ofSeconds(30));
        log.info("{}服务{}响应报文：{}",req.getReqId(),req.getApiCode()+"接口", jsonObject);
        JSONObject resp = new JSONObject();
        if(Optional.ofNullable(jsonObject.getString("code")).orElse("").startsWith("0")){
            resp = Optional.ofNullable(jsonObject.getJSONObject("data"))
                .orElse(new JSONObject());
            JSONObject.toJSON(resp.entrySet().stream().filter(map->!"originalFlowId".equals(map.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue)));
        }else{
            log.warn("flowId:{},code{},msg:{}",req.getReqId(),jsonObject.getString("code"),jsonObject.getString("msg"));
        }
        response(resp,result);
        return result;
    }

    protected abstract void response(JSONObject resp, JSONObject result);

    protected abstract Mono<JSONObject> getWebClient(ApiReq req);

    protected abstract void request(ApiReq req);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
